// ignore_for_file: non_constant_identifier_names, unused_element, dead_code

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:verse_systems/pages/repayment/repayment_control.dart';
import 'package:verse_systems/res/colors.dart';
import 'package:verse_systems/utils/image_utils.dart';
import 'package:verse_systems/widgets/counter_down.dart';
import 'package:verse_systems/widgets/drawer_appbar.dart';
import 'package:verse_systems/widgets/sp_button.dart';
import 'package:verse_systems/widgets/webView_page.dart';

class RepaymentBankInfo extends StatefulWidget {
  const RepaymentBankInfo({super.key});

  @override
  State<RepaymentBankInfo> createState() => _RepaymentBankInfoState();
}

class _RepaymentBankInfoState extends State<RepaymentBankInfo>  with WidgetsBindingObserver {
  final control = Get.put(RepaymentControl());
  final state = Get.find<RepaymentControl>().state;

  @override
  void initState() {
    super.initState();
      WidgetsBinding.instance.addObserver(this);
    control.get_repaymenton_bank_infos();
  }

  @override
  void dispose() {
    super.dispose();
    state.repayment_bank_info_countdown = 0;
    WidgetsBinding.instance.removeObserver(this);
  }

 
   /// 当应用生命周期发生变化时,会回调该方法
  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    debugPrint("当前的应用生命周期状态 : $state");
    if (state == AppLifecycleState.paused) {
      debugPrint("应用进入后台 paused");
    } else if (state == AppLifecycleState.resumed) {
      debugPrint("应用进入前台 resumed");
       Get.until((route) => route.settings.name == '/orderDetails');

    } else if (state == AppLifecycleState.inactive) {
      debugPrint("应用进入非活动状态 inactive");
    } else if (state == AppLifecycleState.detached) {
      debugPrint("应用进入 detached 状态 detached");
    }
  }

  openWed() async {
    String productUrl = state.repayment_bank_info_url.toString();
    if (await canLaunchUrl(Uri.parse(productUrl))) {
      await launchUrl(Uri.parse(productUrl));
    } else {
      throw 'Could not launch $productUrl';
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Colours.system_background_color,
        body: GetBuilder<RepaymentControl>(
            init: control,
            builder: (_) {
              if (state.repayment_bank_info_type == 1) {
                openWed();
                return WebViewPage(
                  url: state.repayment_bank_info_url.toString(),
                  title: "repayment".tr,
                );
              }
              return SizedBox(
                height: MediaQuery.of(context).size.height,
                child: Stack(
                  children: [_confirmUs, _confirmContent],
                ),
              );
            }));
  }

  Widget get _confirmContent {
    return SizedBox(
        child: SingleChildScrollView(
      child: Column(
        children: [
          DrawerAppbar(
            backgroundColor: Colours.app_main_color,
            color: Colours.app_black_text_color,
            title:  "repayment".tr,
            onPressed: () {
              //返回指定页面
              Get.until((route) => route.settings.name == '/orderDetails');
            },
          ),
          _confirmTitle,
          _confirmContainer,
          _confirmVoucher,
          _confirmNotice,
          _confirmPressed
        ],
      ),
    ));
  }

  Widget get _confirmNotice {
    return Container(
      padding: EdgeInsets.symmetric(vertical: 15.w, horizontal: 15.w),
      margin: EdgeInsets.symmetric(
          horizontal: (MediaQuery.of(context).size.width - 350.w) / 2,
          vertical: 5.w),
      width: 350.w,
      child: Text(
        state.repayment_bank_info_notice.toString(),
        textAlign: TextAlign.left,
        style: TextStyle(
          color: Colours.app_forward_color,
          fontSize: 12.sp,
        ),
      ),
    );
  }

  Widget get _confirmVoucher {
    if (state.dataBank!.vouchers == false) {
      return Container(
        margin: EdgeInsets.fromLTRB(0, 48.w, 0, 0.w),
      );
    }
    return Container(
        margin: EdgeInsets.fromLTRB(0, 42.w, 0, 48.w),
        child: Column(
          children: [
            InkWell(
              onTap: control.openAlbum,
              child: (state.repayment_bank_info_voucher == "")
                  ? Image.asset(
                      ImageUtils.getImgPath("voucher"),
                      fit: BoxFit.fill,
                      width: 182.w,
                      height: 103.w,
                    )
                  : CachedNetworkImage(
                      fit: BoxFit.fill,
                      width: (MediaQuery.of(context).size.width - 65.w) / 2,
                      height: 106.w,
                      imageUrl: state.repayment_bank_info_voucher.toString(),
                      placeholder: (context, url) => Transform.scale(
                        scale: 0.3,
                        child: const CircularProgressIndicator(
                          color: Colours.app_main_background_color,
                        ),
                      ),
                      errorWidget: (context, url, error) =>
                          const Icon(Icons.error),
                    ),
            ),
            SizedBox(height: 21.w),
            Text(
              "upload_voucher_submit".tr,
              style: TextStyle(
                color: Colours.app_main_background_color,
                fontSize: 12.sp,
              ),
            ),
          ],
        ));
  }

  Widget get _confirmTitle {
    return Container(
        margin: EdgeInsets.fromLTRB(0, 42.w, 0, 25.w),
        child: Column(
          children: [
            Text(
              state.repayment_bank_info_repay_amount.toString(),
              style: TextStyle(
                  color: Colours.app_main_color,
                  fontSize: 42.sp,
                  fontWeight: FontWeight.w700),
            ),
            SizedBox(height: 21.w),
            (state.repayment_bank_info_countdown == 0)
                ? Container()
                : CounterDownPage(
                    countdown: state.repayment_bank_info_countdown)
          ],
        ));
  }

  Widget get _confirmPressed {
    if (state.dataBank!.vouchers == false) {
      return Container();
    }
    return Container(
      margin: EdgeInsets.fromLTRB(0, 50.w, 0, 30.w),
      child: SizedBox(
          width: 310.w,
          child: SPButton(
            minHeight: 50.w,
            fontSize: 18.sp,
            text: "repayment".tr,
            radius: 25.w,
            textColor: Colours.app_main_color,
            backgroundColor: Colours.app_main_background_color,
            onPressed: control.repayment_bank_info_onPressed,
          )),
    );
  }

  Widget get _confirmContainer {
    return Container(
      padding: EdgeInsets.symmetric(vertical: 15.w, horizontal: 15.w),
      margin: EdgeInsets.symmetric(
          horizontal: (MediaQuery.of(context).size.width - 350.w) / 2,
          vertical: 5.w),
      width: 350.w,
      decoration: BoxDecoration(
          borderRadius: BorderRadius.all(Radius.circular(10.w)),
          color: Colours.app_main_color,
          boxShadow: [
            BoxShadow(
                color: Colours.stringAnAlphaColor("0xff000000", alpha: 0.08),
                offset: const Offset(0.0, 15.0), //阴影xy轴偏移量
                blurRadius: 25.0, //阴影模糊程度
                spreadRadius: 0.5 //阴影扩散程度
                )
          ]),
      child: Column(
        children: _payment_list,
      ),
    );
  }

  List<Widget> get _payment_list {
    return [
      {"title": "payee_bank".tr, "value": state.dataBank!.bankName},
      {"title": "payee_name".tr, "value": state.dataBank!.realName},
      {"title": "bank_account".tr, "value": state.dataBank!.bankNumber}
    ].map((value) {
      return Column(
        children: [
          Container(
            margin: EdgeInsets.symmetric(vertical: 13.w),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Row(
                  children: [
                    Text(
                      value["title"].toString(),
                      style: TextStyle(
                        color: Colours.app_text_color,
                        fontSize: 14.sp,
                      ),
                    ),
                    InkWell(
                        onTap: () {
                          final String title = value["title"].toString();
                          Clipboard.setData(ClipboardData(
                                  text: value["value"].toString()))
                              .then((value) {
                            Get.snackbar(title, "copy_successful".tr);
                          });
                        },
                        child: Container(
                          padding: EdgeInsets.symmetric(
                              horizontal: 10.w, vertical: 3.w),
                          margin: EdgeInsets.symmetric(horizontal: 15.w),
                          decoration: BoxDecoration(
                            borderRadius:
                                BorderRadius.all(Radius.circular(8.5.w)),
                            color: Colours.stringAnAlphaColor("0xffD6B875",
                                alpha: 0.45),
                          ),
                          child: Text(
                            "copy".tr,
                            style: TextStyle(
                              color: Colours.app_copy_text_color,
                              fontSize: 10.sp,
                            ),
                          ),
                        ))
                  ],
                ),
                Text(
                  value["value"].toString().trim(),
                  style: TextStyle(
                    color: Colours.app_black_text_color,
                    fontSize: 13.sp,
                  ),
                ),
              ],
            ),
          ),
          Container(
            height: 1.w,
            color: Colours.app_text_line_color,
          ),
        ],
      );
    }).toList();
  }

  Widget get _confirmUs {
    return Container(
        height: 300.w,
        decoration: BoxDecoration(
          image: DecorationImage(
              image: ExactAssetImage(ImageUtils.getImgPath("loan_background")),
              fit: BoxFit.fill),
        ));
  }
}
